﻿// -----------------------------------------------------------------------
//  <copyright file="LoggingModule.cs" company="LiuliuSoft">
//      Copyright (c) 2025 66SOFT. All rights reserved.
//  </copyright>
//  <site>https://ifs.66soft.net</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-10-15 10:10</last-date>
// -----------------------------------------------------------------------

using System.ComponentModel;
using System.Diagnostics;

using DaprPlus.AspNetCore;
using DaprPlus.Builder;

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

using Serilog;


namespace Shares.Infrastructure.Logging;

[Description("日志模块")]
public class LoggingModule : AspModuleBase
{
    /// <summary>
    /// 获取 模块级别，级别越小越先启动
    /// </summary>
    public override ModuleLevel Level => ModuleLevel.Framework;

    /// <summary>
    /// 将模块服务添加到依赖注入服务容器中
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <returns></returns>
    public override IServiceCollection AddServices(IServiceCollection services)
    {
        var builder = services.GetSingletonInstanceOrNull<WebApplicationBuilder>();
        if (builder == null)
        {
            return services;
        }

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(builder.Configuration)
            .CreateLogger();
        services.AddSerilog();

        return base.AddServices(services);
    }

    /// <summary>
    /// 应用AspNetCore的服务业务
    /// </summary>
    /// <param name="app">Web应用程序</param>
    public override Task UseModule(WebApplication app)
    {
        app.UseSerilogRequestLogging(opts =>
        {
            opts.EnrichDiagnosticContext = (ctx, http) =>
            {
                ctx.Set("ClientIp", http.Connection.RemoteIpAddress?.ToString() ?? "0.0.0.0");
                ctx.Set("UserAgent", http.Request.Headers.UserAgent.ToString());
            };
        });
        app.UseMiddleware<CorrelationIdMiddleware>();

        return base.UseModule(app);
    }
}